package com.ecloud.discovery.eureka.api;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ecloud.discovery.eureka.model.Microservice;

@RestController
@RequestMapping("/discovery")
public class RegistryServiceController {
  @Autowired
  private DiscoveryClient discoveryClient;

  @GetMapping("/registered")
  public  Object registeredList() {
    return getServices();
  }

  public List<Microservice> getServices() {
    List<Microservice> serviceList = new ArrayList<Microservice>();
    for (String serviceName : discoveryClient.getServices()) {
      Microservice microservice = new Microservice();
      microservice.setName(serviceName);
      List<ServiceInstance> list = discoveryClient.getInstances(serviceName);
      microservice.setInstances(list);
      serviceList.add(microservice);
    }
    return serviceList;
  }
}
